<template>
  <el-form
    ref="resetRef"
    :model="resetPwd"
    :rules="pwdRules"
    class="pwd-form login-form w-550px"
  >
    <div class="flex justify-between items-center py-10px" v-if="active !== 3">
      <div class="font-semibold text-17px">重置密码</div>
      <div
        class="cursor-pointer text-14px"
        style="color: #409eff"
        @click="backLogin"
        v-if="active === 1"
      >
        返回账号登录
      </div>
    </div>
    <div class="pl-15px pwdSteps my-30px" v-if="active !== 3">
      <div>
        <div class="flex items-center">
          <div class="circle" :class="active > 1 ? 'hollow' : ''"></div>
          <div class="pwdLine" :class="active >= 1 ? 'bg-4a9fe9' : ''"></div>
        </div>
        <div class="mt-10px -translate-x-1.5/4 text-center w-100px">
          验证员工对应手机号码
        </div>
      </div>
      <div>
        <div class="flex items-center">
          <div class="pwdLine" :class="active >= 2 ? 'bg-4a9fe9' : ''"></div>
          <div class="circle"></div>
          <div class="pwdLine" :class="active >= 2 ? 'bg-4a9fe9' : ''"></div>
        </div>
        <div class="text-center mt-10px">设置新密码</div>
      </div>
      <div>
        <div class="flex items-center">
          <div class="pwdLine"></div>
          <div class="circle"></div>
        </div>
        <div class="mt-10px translate-x-1.5/4 text-center">密码重置成功</div>
      </div>
    </div>
    <el-form-item prop="employeeNo" v-if="active === 1">
      <el-input
        v-model.trim="resetPwd.employeeNo"
        placeholder="请输入工号"
        size="large"
        :prefix-icon="User"
        class="ml-0.7/4"
        style="width: 65%"
      />
    </el-form-item>
    <el-form-item prop="checkCode" v-if="active === 1">
      <el-input
        v-model.trim="resetPwd.checkCode"
        placeholder="请输入短信验证码"
        size="large"
        :prefix-icon="Message"
        class="ml-0.7/4"
        style="width: 65%"
      >
        <template #suffix>
          <el-button
            link
            style="color: #409eff"
            :disabled="clicked"
            @click="getMsg"
            :class="clicked ? 'clicked' : ''"
            key="autoButton"
            >{{ msgText }}</el-button
          >
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="newPassword" v-if="active === 2">
      <el-input
        v-model.trim="resetPwd.newPassword"
        placeholder="请输入8-16位，含大小写、数字及特殊字符"
        type="password"
        show-password
        size="large"
        class="ml-0.7/4"
        style="width: 65%"
      >
        <template #prefix
          ><svg-icon
            icon-class="password"
            class="el-input__icon input-icon" /></template
      ></el-input>
    </el-form-item>
    <el-form-item prop="confirmPassword" v-if="active === 2">
      <el-input
        v-model.trim="resetPwd.confirmPassword"
        placeholder="请确认新密码"
        type="password"
        show-password
        size="large"
        class="ml-0.7/4"
        style="width: 65%"
      >
        <template #prefix
          ><svg-icon
            icon-class="password"
            class="el-input__icon input-icon" /></template
      ></el-input>
    </el-form-item>
    <div v-if="active === 3" class="imgBox">
      <img src="@/assets/icons/svg/success-filled.svg" alt="dark" />
      <h2>密码重置成功</h2>
      <p>{{ resetTip }}</p>
    </div>
    <el-button
      type="primary"
      size="large"
      class="w-2.6/4 ml-0.7/4"
      @click="next"
      :disabled="btnDisable"
      >{{ stepsText }}</el-button
    >
    <p class="w-full text-center mt-10px leading-16px">
      {{ checkCodeMsg }}
    </p>
  </el-form>
</template>

<script setup name="ForgotPwd">
import { sendYzmMsg, checkYzmMsg, updateNewPwd } from '@/api/login'
import { Message, User } from '@element-plus/icons-vue'
import { getCurrentInstance, ref } from 'vue'
const { proxy } = getCurrentInstance()

const data = reactive({
  resetPwd: {
    newPassword: '',
    confirmPassword: '',
    employeeNo: '',
    checkCode: ''
  }
})
const { resetPwd } = toRefs(data)

/*** ***忘记密码*** ***/

// 步骤
const active = ref(1)
// 按钮文字
const stepsText = ref('下一步')
// 操作按钮disable
const btnDisable = computed(() => {
  if (active.value === 1) {
    if (!resetPwd.value.employeeNo || !resetPwd.value.checkCode) {
      return true
    } else {
      return false
    }
  } else if (active.value === 2) {
    if (!resetPwd.value.newPassword || !resetPwd.value.confirmPassword) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
})

const emit = defineEmits(['update:forget'])

function backLogin() {
  active.value = 1
  stepsText.value = '下一步'
  checkCodeMsg.value = ''
  emit('update:forget', false)
}

const checkCode = ref('')
const resetTip = ref('6秒后自动跳转至系统登录页')
const resetInterval = ref(null)
async function next() {
  if (active.value === 3) {
    active.value = 1
    emit('update:forget', false)
    resetPwd.value = {}
    return
  }
  if (active.value === 2) {
    proxy.$refs.resetRef.validate(valid => {
      if (valid) {
        updateNewPwd({
          code: checkCode.value,
          employeeNo: resetPwd.value.employeeNo,
          newPassword: resetPwd.value.newPassword
        }).then(res => {
          if (res.code === 200) {
            active.value++
            stepsText.value = '立即前往'
            let seconds = 6
            resetTip.value = seconds + '秒后自动跳转至网站首页'
            resetInterval.value = setInterval(() => {
              seconds--
              resetTip.value = seconds + '秒后自动跳转至网站首页'
              if (seconds <= 0) {
                clearInterval(resetInterval.value)
                resetPwd.value = {}
                backLogin()
              }
            }, 1000)
          }
        })
      }
    })
  }
  if (active.value === 1) {
    if (!resetPwd.value.employeeNo || !resetPwd.value.checkCode) {
      return
    }
    checkYzmMsg({
      employeeNo: resetPwd.value.employeeNo,
      yzm: resetPwd.value.checkCode
    }).then(res => {
      if (res.code === 200) {
        checkCode.value = res.data
        active.value++
        checkCodeMsg.value = ''
        resetPwd.value.checkCode = ''
        stepsText.value = '完成'
      }
    })
  }
}
const validatePass = (rule, value, callback) => {
  //必须包含⼤⼩写字母、数字、特殊字符长度再9-16位之间
  var regex = /^(?![^a-zA-Z]+$)(?!\D+$)(?![a-zA-Z0-9]+$).{8,16}$/
  if (value === '') {
    callback(new Error('请输⼊密码'))
  } else if (value.length < 8 || value.length > 16) {
    callback(new Error('请输⼊8~16位密码'))
  } else if (!regex.test(value)) {
    callback(
      new Error('请输入包含英文字母大小写、数字和特殊符号的 8-16 位组合')
    )
  } else {
    callback()
  }
}

const equalToPassword = (rule, value, callback) => {
  if (resetPwd.value.newPassword !== value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}
const pwdRules = ref({
  // oldPassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { required: true, validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
})

// 获取验证码
const clicked = ref(false)
const msgText = ref('获取验证码')
const msgTime = ref(null)
const checkCodeMsg = ref('')
// 忘记密码

function checkCodeCountDown() {
  // 倒计时未结束 按钮状态不改变
  const msg = localStorage.getItem('msgTime')
  const time = new Date().getTime()
  if (msg && time - msg <= 60 * 1000) {
    // 计算60秒倒计数剩余时间
    let second = Math.ceil(60 - (time - msg) / 1000)
    clicked.value = true
    msgText.value = second + '秒后可重新获取'
    msgTime.value = setInterval(() => {
      second--
      msgText.value = second + '秒后可重新获取'
      if (second <= 0) {
        clicked.value = false
        localStorage.removeItem('msgTime')
        clearInterval(msgTime.value)
        msgText.value = '获取验证码'
      }
    }, 1000)
  } else {
    localStorage.removeItem('msgTime')
  }
}
checkCodeCountDown()
// 获取验证码
function getMsg() {
  if (!resetPwd.value.employeeNo) {
    proxy.$modal.msgError('请输入工号')
    return
  }
  sendYzmMsg({ employeeNo: resetPwd.value.employeeNo }).then(res => {
    if (res.code === 200) {
      checkCodeMsg.value = res.msg
      let second = 60
      clicked.value = true
      msgText.value = second + '秒后可重新获取'
      const time = new Date().getTime()
      //   记录倒计时开始时间
      localStorage.setItem('msgTime', time)
      msgTime.value = setInterval(() => {
        second--
        msgText.value = second + '秒后可重新获取'
        if (second <= 0) {
          clicked.value = false
          localStorage.removeItem('msgTime')
          clearInterval(msgTime.value)
          msgText.value = '获取验证码'
        }
      }, 1000)
    }
  })
}
</script>

<style scoped lang="scss">
.pwdSteps {
  @apply flex;
  .circle {
    height: 12px;
    width: 12px;
    border-radius: 50%;
    background-color: #4a9fe9;
    position: relative;
    z-index: 2;
  }
  .hollow {
    background-color: white;
    border: 2px solid #4a9fe9;
  }
  .pwdLine {
    width: 100px;
    height: 2px;
    background-color: #e5dede;
    position: relative;
    z-index: 1;
  }
  .bg-4a9fe9 {
    @apply bg-#4a9fe9;
  }
}
.pwd-form {
  margin-right: 0 !important;
  @apply pb-80px;
  :deep(.el-form-item__error) {
    left: 17.5% !important;
  }
  .clicked {
    color: #e5dede !important;
    font-size: 13px;
  }
}

.imgBox {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  img {
    width: 100px;
    height: auto;
  }
  h2 {
    font-weight: 600;
  }
  p {
    color: #817b7b;
  }
}
</style>
